<template>
  <el-checkbox-group class="role-app" v-model="checkApps" :disabled="appsDisabled">
    <div v-for="(area,index) in apps" :key="index">
      <!-- <div>{{area.name}}</div> -->
      <div v-for="(group,index) in area.children" :key="index">
        <div>
          <div style="font-size:14px;">{{group.name}}</div>
          <div>
            <el-card class="item" v-for="(app,index) in group.children" :key="index" :body-style="{padding:'10px'}">
              <el-checkbox :label="app.id" @change="appChange(app.id)">{{app.name}}</el-checkbox>
            </el-card>
          </div>
        </div>
      </div>
    </div>
  </el-checkbox-group>
</template>

<script>
export default {
  components: {},
  props: {
    appsDisabled: {
      type: Boolean,
      default: function() {
        return true;
      }
    },
    role: {
      type: Object,
      default: function() {
        return {};
      }
    }
  },
  data() {
    return {
      apps: [],
      checkApps: []
    };
  },
  created() {
    this.getAllApp();
  },
  watch: {
    role: {
      handler: function() {
        this.clear();
        if (this.role != undefined && Object.keys(this.role).length > 0) {
          this.$http({
            url: "/core/api/apps-by-roleid/" + this.role.id,
            method: "GET"
          }).then(resp => {
            this.checkApps = resp.data;
          });
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    clear() {
      this.checkApps = [];
    },
    getAllApp() {
      this.$http({
        url: this.$URL_ADDR.core.app.all,
        method: "GET"
      }).then(resp => {
        this.apps = resp.data;
      });
    },
    appChange(appid) {
      var isChecked = false;
      for (var i = 0; i < this.checkApps.length; i++) {
        if (appid === this.checkApps[i]) {
          isChecked = true;
        }
      }
      if (isChecked) {
        this.addApp(appid);
      } else {
        this.deleteApp(appid);
      }
    },
    addApp(appid) {
      this.$http({
        url: "/core/api/secu-role-apps",
        method: "POST",
        data: {
          roleId: this.role.id,
          appId: appid
        }
      }).then(() => {
        this.$message({
          type: "success",
          message: "添加授权成功!"
        });
      });
    },
    deleteApp(appid) {
      this.$http({
        url: "/core/api/deleteByRoleIdAndAppId",
        method: "DELETE",
        params: {
          roleId: this.role.id,
          appId: appid
        }
      }).then(() => {
        this.$message({
          type: "success",
          message: "取消授权成功!"
        });
      });
    }
  }
};
</script>
<style lang="less" scoped>
.role-app {
  margin: 10px 0;
  .item {
    width: 180px;
    height: 40px;
    display: inline-block;
    margin: 10px 10px 10px 0;
  }
}
</style>

